import numpy as np
import sys
delim = "\t"

def _read_ascii_data(filename, comment_char, delim):
    print "reading", filename
    fh = open(filename, "r")
    data = []
    for line in fh.xreadlines():
        line = line.lstrip()
        line = line.replace("\n", "")
        if line.find(comment_char)is not 0:
            dl = line.split(delim)
            tmp = []
            for cc in range(len(dl)):
                tmp.append(_convert_to_number(dl[cc]))
            data.append(tmp)
    fh.close()

    print "constructing numpy array ", len(data), "x", len(data[0])
    ar = np.array(data)
    return ar


def _read_rfdata_file(filename):
    global delim
    return _read_ascii_data(filename, "*", delim)


def _read_rftrial_file(filename):
    global delim
    comment_char = "*"
    print "reading", filename
    fh = open(filename, "r")
    trials = []
    cnt = 0
    for line in fh.xreadlines():
        cnt += 1
        line = line.lstrip()
        line = line.replace("\n", "").rstrip()
        if cnt > 2:
            if line.find(comment_char)is not 0:
                dl = line.split(delim)
                tmp = []
                for cc in range(len(dl)):
                    tmp.append(_convert_to_number(dl[cc]))
                trials.append(tmp)
        elif cnt == 2:  #varname
            varnames = line.split(delim)

    fh.close()
    return np.array(trials), varnames

def _convert_to_number(num_str):
    """
    returs np.int32 or np.float32 and None not convertabel to number (catches exceptions)
    
    """
    if num_str.find(".") >= 0:
        try:
    	   rtn = np.float32(num_str)
           return rtn
        except:
            return None
    else:
        try:
    	   rtn = np.int32(num_str)
    	   return rtn
        except:
            return None


def convert_force_files(filename):
    suffix = ".rf.npz"
    filename = filename.split(".")[0]
    trials, varname = _read_rftrial_file(filename + ".rftrial")
    rfdata = _read_rfdata_file(filename + ".rfdata")
    print "saving " + suffix + "-file:", filename
    np.savez(filename + suffix, trials=trials, varnames=varname, data=rfdata)

def load_force_data(filename):
    """return trails, varnames, rf-data"""
    suffix = ".rf.npz"
    f = np.load(filename + suffix)
    return f['trials'], f['varnames'], f['data']
#---------------------------------------------------------------------------


#convert_force_files("fonarc1_9")
tr, va, rfd = load_force_data("fonarc1_9")








